# coding: utf-8

"""
harbor镜像管理
"""

import os
import logging as logger


class Docker:
    def __init__(self, host, user, passwd):
        self.is_login = False
        self.host = host
        self.user = user
        self.passwd = passwd

    def login(self):
        if self.is_login == False:
            self.__login__(host=self.host, user=self.user, passwd=self.passwd)
            self.is_login = True

    def __login__(self, host, user, passwd):
        assert os.system("docker login -u {} -p {} {}".
                         format(user, passwd, host)) == 0, "Harbor login fail."

    def build(self, image_address, dockerfile, workspace='.'):
        self.login()
        assert os.system("docker build --rm -t {} -f {} {}".
                         format(image_address, dockerfile, workspace)) == 0, "Harbor build fail."

    def push(self, image_address):
        self.login()
        assert os.system("docker push {}".format(image_address)) == 0, "Harbor push fail."

    def pull(self, image_address):
        self.login()
        assert os.system("docker pull {}".format(image_address)) == 0, "Harbor pull fail."

    def rm(self, image_address):
        self.login()
        try:
            assert os.system("docker rmi {}".format(image_address)) == 0
        except:
            logger.warning("Harbor rm fail.")
